/**
 * author:Administrator
 * date:2013-5-21
 */
package com.roc.web.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;

/**
 * @author Administrator
 *
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/manage")
public class MerchantManageAction extends PaginationBaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5236170890634487270L;
	
	private Logger logger=LogManager.getLogger(MerchantManageAction.class);
	
	private Operators merchant;
	
	private MerchantManageSearchCondition searchCondition;

	private List<Object> profitRsList=new ArrayList<Object>();
	
	
	@Autowired 
	IMerchantServices merchantServices;
	@Autowired
	IPagenitionService pagenitionService;
	
	@Autowired
	IorgService orgService;
	

	@Action(value = "search", results = { @Result(name = "success", location = "/pages/merchantAdminView.jsp"),
            @Result(name="error",location="/pages/merchantAdminView.jsp"),
            @Result(name="login",location="/pages/redirect.jsp") })

	public String search() throws Exception{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(searchCondition==null){
			searchCondition=(MerchantManageSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new MerchantManageSearchCondition();
			}
		}
		try {
			if(Constance.MERCHANT_TYPE_CAIWU.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_STORE.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_MARKET.equals(logingMerchant.getRoleType())){
				if("99".equals(searchCondition.getRoleType())){
					searchCondition.setRoleType(Constance.MERCHANT_TYPE_DAILI);
				}
				
			}
			if(Constance.MERCHANT_TYPE_CAIWU.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_STORE.equals(logingMerchant.getRoleType())){
					searchCondition.setSuperiorId(1);
			
			}
			if(Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant.getRoleType())){
				//searchCondition.setSuperiorId(logingMerchant.getId());
				searchCondition.setRoleType(Constance.MERCHANT_TYPE_DAILI);
				List<Operators> mList=merchantServices.listAllSubMerchants(logingMerchant.getId());
				searchCondition.setMerchantNos(dealSomeData(mList));
				//System.out.println(searchCondition.getFullSearchHQL(null));
				
			}
			org();
			//this.setCurrentPage(this.checkCurrentPage());
			int rows=pagenitionService.count(searchCondition);
			searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			if(searchRsList!=null&&searchRsList.size()>0){
				List<Object> tempList=new ArrayList<Object>();
				Map<String, Operators> mapMerchant=merchantServices.listAllMerchants(logingMerchant.getRoleType(), logingMerchant.getId(),logingMerchant.getOrgCode());
				for(Object o:searchRsList){
					Operators m=(Operators)o;
					if(mapMerchant.get(m.getSuperiorId()+"")==null){
					 m.setSuperMerchant(new Operators());
					}else {
						m.setSuperMerchant(mapMerchant.get(m.getSuperiorId()+""));
					}
					m.setMerLevelDesc(ConfigProperties.getAgentType(m.getAgentType()));
					tempList.add(m);
				}
				searchRsList.clear();
				searchRsList=tempList;
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		return SUCCESS;
	}
	
	public void org() throws Exception{
		Operators loginMerchant = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		    List orgList=new ArrayList();
			
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_RECOMANFER.equals(logingMerchant.getRoleType())){
				OrgBean org = new OrgBean();
				org=orgService.queryOrgByCode(logingMerchant.getOrgCode());
				orgList.add(org);
			}else if(Constance.MERCHANT_TYPE_CAIWU.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_STORE.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_MARKET.equals(logingMerchant.getRoleType())){
				orgList=orgService.lisOrgByMerchantId(logingMerchant.getId());
			}else{
			
				orgList=orgService.queryOrgList();
			}
			
			getRequest().setAttribute("orgList", orgList);
			
			Map<String, String> merLevels=ConfigProperties.getAgentTypeProperties();
			getRequest().setAttribute("merLevels", merLevels);
		
	}
	
	@Action(value = "merchantAdminView", results = {
			@Result(name = "success", location = "/pages/merchantAdminView.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	public String merchantView()throws Exception  {
		initSomeDataForAction();
		List orgList=new ArrayList();
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_RECOMANFER.equals(logingMerchant.getRoleType())){
				orgList=orgService.lisOrgByCode(logingMerchant.getOrgCode());
			}else if(Constance.MERCHANT_TYPE_CAIWU.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_STORE.equals(logingMerchant.getRoleType())||
					Constance.MERCHANT_TYPE_MARKET.equals(logingMerchant.getRoleType())){
				orgList=orgService.lisOrgByMerchantId(logingMerchant.getId());
			}else{
			
				orgList=orgService.queryOrgList();
			}
			
			
			Map<String, String> merLevels=ConfigProperties.getAgentTypeProperties();
			getRequest().setAttribute("orgList", orgList);
			getRequest().setAttribute("merLevels", merLevels);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			addActionError("加载代理商基本信息出错！！");
		}
		return SUCCESS;
	}
	
	//------------------注销代理商-----------------------------
	
	@Action(value = "cancelMerchant", results = {
			@Result(name = "success", location = "/pages/merchantAdminView.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	public String cancelMerchant()throws Exception  {
		initSomeDataForAction();
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(merchant==null){
			return search();
		}
		try {
			merchantServices.cancelMerchant(merchant, logingMerchant.getAccountNo());
			logger.info("系统管理员【"+logingMerchant.getAccountNo()+"】成功注销了【"+merchant.getAccountNo()+"】");
			addActionMessage("系统管理员【"+logingMerchant.getAccountNo()+"】成功注销了【"+merchant.getAccountNo()+"】");
			
			return search();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		
	}
	
	@Action(value = "recoverMerchant", results = {
			@Result(name = "success", location = "/pages/merchantAdminView.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	public String recoverMerchant()throws Exception  {
		initSomeDataForAction();
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(merchant==null){
			return search();
		}
		try {
			merchantServices.recoverMerchant(merchant, logingMerchant.getAccountNo());
			logger.info("系统管理员【"+logingMerchant.getAccountNo()+"】成功恢复了【"+merchant.getAccountNo()+"】的状态");
			addActionMessage("系统管理员【"+logingMerchant.getAccountNo()+"】成功恢复了【"+merchant.getAccountNo()+"】的状态");
			
			return search();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		
	}
	
	@Action(value = "toModifyMerchantInfo", results = {
			@Result(name = "success", location = "/pages/modifyMerinfo.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	public String toModifyMerchantInfo()throws Exception  {
		initSomeDataForAction();
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(merchant==null){
			return search();
		}
		try {
			merchantView();
			merchant=merchantServices.findMerchantByNo(merchant.getAccountNo());
		   // addActionMessage("代理商【"+merchant.getAccountNo()+"】的基本信息修改成功");
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	@Action(value = "modifyMerchantInfo", results = {
			@Result(name = "success", location = "/pages/modifyMerinfo.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	public String modifyMerchantInfo()throws Exception  {
		initSomeDataForAction();
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(merchant==null){
			return SUCCESS;
		}
		try {
			merchantView();
			merchant=merchantServices.modifyMerchant(merchant,logingMerchant.getAccountNo());
			logger.info("系统管理员【"+logingMerchant.getAccountNo()+"】成功修改了代理商【"+merchant.getAccountNo()+"】的基本信息");
			
			addActionMessage("系统管理员【"+logingMerchant.getAccountNo()+"】成功修改了代理商【"+merchant.getAccountNo()+"】的基本信息");
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	
	@Action(value = "resetPwd", results = {
			@Result(name = "success", location = "/pages/merchantAdminView.jsp"),
			@Result(name = "error", location = "/error.jsp") }, interceptorRefs = @InterceptorRef("defaultStack")

	)
	public String resetPassword() throws Exception {
		Operators loginMerchant = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		// loginMerchant = new Merchant();
		// loginMerchant.setMerType("00");
		try {
		//	merchantServices.resetPassword(loginMerchant, merchant.getId());
			merchant=merchantServices.loadMerchat(merchant.getId());
			if(merchant!=null){
				if(Constance.MERCHANT_TYPE_DAILI.equals(merchant.getRoleType())){
					addActionMessage("代理商【"+merchant.getAccountNo()+"】的密码重置成功");
				}else {
					addActionMessage("推荐人【"+merchant.getAccountNo()+"】的密码重置成功");
				}
			}
			logger.info("系统管理员【"+loginMerchant.getAccountNo()+"】成功重置了【"+merchant.getAccountNo()+"】的密码");
		} catch (ServiceException e) {
			logger.info(e.getMessage());
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return search();
	}
	
	
	
	

	@Action(value = "recomanderQuery", results = {
			@Result(name = "success", location = "/pages/recomenderQuery.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	public String recomanderQuery()throws Exception  {
		initSomeDataForAction();
		if(merchant==null){
			addActionMessage("查询推荐人详细信息出错");
			return ERROR;
		}
		try {
			merchant=merchantServices.loadMerchat(merchant.getId());
			List<Operators> recMerchants=merchantServices.findRecomenderMerchant(merchant.getId());
			
			if(recMerchants!=null&&recMerchants.size()>0){
				searchRsList.clear();
				for(Operators mer:recMerchants){
					searchRsList.add(mer);
				}
			}
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		return SUCCESS;
	}
	
	public void initSomeDataForAction() {
		
	}
	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		// TODO Auto-generated method stub
		
	}
	private String[] dealSomeData(List<Operators> list){
		String[] str=null;
		if(list!=null&&list.size()>0){
			str=new String[list.size()];
			for(int i=0;i<list.size();i++){
				str[i]=list.get(i).getAccountNo();
			}
		}
		return str;
	}
	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getInitPageSize()
	 */
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (MerchantManageSearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_MERCHANT_MANAGE);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_MERCHANT_MANAGE, searchCondition);
	}
	/**
	 * @return the searchCondition
	 */
	public MerchantManageSearchCondition getSearchCondition() {
		
		return searchCondition;
	}
	/**
	 * @param searchCondition the searchCondition to set
	 */
	public void setSearchCondition(MerchantManageSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	/**
	 * @return the merchant
	 */
	public Operators getMerchant() {
		return merchant;
	}
	/**
	 * @param merchant the merchant to set
	 */
	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}


	

	/**
	 * @return the profitRsList1
	 */
	public List<Object> getProfitRsList() {
		return profitRsList;
	}


	/**
	 * @param profitRsList1 the profitRsList1 to set
	 */
	public void setProfitRsList1(List<Object> profitRsList) {
		this.profitRsList = profitRsList;
	}


	
	

}
